import { Component, OnInit } from '@angular/core';
import { BladeContainerInterface } from "../../../../shared/blade/blade-container.interface";
import { Blade } from "../../../../shared/blade/blade.model";
import { Observable } from "rxjs/Observable";
import { FormBuilder, FormGroup, Validators, FormControl, ValidatorFn, AbstractControl } from "@angular/forms";
import { SimpleChanges } from "@angular/core/core";
import { SetofkeyService } from "../../../../service/setofkey.service";
import { Setofvalue } from "../../../../entity/setofvalue.model";
import { Command } from "../../../../shared/toolbar.service";
import { SetofvalueService } from "../../../../service/setofvalue.service";
import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";
import { BladeData } from "../../../../shared/blade/blade-data";
import { MyValidators } from "../../../../utils/validator/rang";

// import { Subject } from "rxjs/Subject";
// // Observable class extensions
// import 'rxjs/add/observable/of';
// // Observable operators
// import 'rxjs/add/operator/catch';
// import 'rxjs/add/operator/debounceTime';
// import 'rxjs/add/operator/distinctUntilChanged';

@Component({
    selector: 'app-dic-value-edit',
    templateUrl: './dic-value-edit.component.html',
    styleUrls: ['./dic-value-edit.component.css']
})
export class DicValueEditComponent extends BladeContainerBase<Setofvalue>{

    constructor(
        private fb: FormBuilder,
        private setofvalueService: SetofvalueService) {
        super(fb);
    }

    ngOnInit(): void {
        //编辑时注册按钮和按钮命令    
        if (!this.isNew) {
            this.commands = [
                new Command("save", "保存", "fa fa-save", "setofkey:update", (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
                new Command("reset", "重置", "fa fa-save", "setofkey:reset", (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
            ]
        }
        else {
            this.currentEntity = new Setofvalue(0, this.parentEntity.keyId, "", "", false, 0);
        }
        super.ngOnInit();
    }
    /**
     * 初始化数据
     * 
     * 
     * @memberof DicValueEditComponent
     */
    initData(): any | Observable<any> | Promise<any> {
        this.formPatchValue(this.currentEntity);
    }

    exeSaveChange(blade: any): void {
        this.saveChange();
    }
    canSaveChange(blade: any): boolean {
        return this.hasChange() && !this.hasError();
    }
    exeReset(blade: any): void {
        return this.formGroup.reset(this.currentEntity);
    }
    canReset(blade: any): boolean {
        return this.hasChange();
    }
    /**
    * 创建表单
    * 
    * 
    * @memberof DicKeyEditComponent
    */
    createForm() {
        this.formGroup = this.fromBuider.group({
            "valueCode": [this.currentEntity.valueCode, [
                Validators.required,
                Validators.pattern("^[A-Za-z0-9]+$"),
                Validators.maxLength(20),
            ], (control: FormControl): any => this.valueCodeAsnyValidator(control)],
            "valueDisplay": [this.currentEntity.valueDisplay, [
                Validators.required,
                Validators.maxLength(80)
            ], (control: FormControl): any => this.valueDisplayAsnyValidator(control)],
            "valueSeq": [this.currentEntity.valueSeq, [
                MyValidators.rang(0, 65535),
                Validators.required
            ]],
            "valueDefault": [this.currentEntity.valueDefault],
        });
    }
    /**
    * 设置表单错误对象
    * 
    * 
    * @memberof BladeContainerBase
    */
    setFormError(): void {
        this.formErrors = {
            'valueCode': '',
            'valueDisplay': '',
            'valueSeq': '',
            'valueDefault': '',
        };
    }
    /**
    * 设置表单验证信息
    * 
    * 
    * @memberof BladeContainerBase
    */
    setValidationMessages(): void {
        this.validationMessages = {
            'valueCode': {
                'required': '值不能为空。',
                'pattern': '值必须由字母和数字组成。',
                'maxlength': '值不能多于20个字符长度。',
                'exist': '值已存在。',
            },
            'valueDisplay': {
                'required': '值名称不能为空。',
                'maxlength': '值名称不能多于80个字符长度。',
                'exist': '值名称已存在。',
            },
            'valueSeq': {
                'required': '值序号不能为空。',
                'rang': '值序号范围是0~65535的整数。',
            }
        };
    }
    /**
     * 异步校验valueCode是否存在
     * 
     * @param {FormControl} control 
     * @returns {Promise<true>} 
     * 
     * @memberof DicKeyEditComponent
     */
    valueCodeAsnyValidator(control: FormControl): any {
        return this.setofvalueService.hasValueCode(control.value, this.currentEntity.valueId, this.currentEntity.keyId)
            .map(res => res ? { exist: true } : null);
    }
    /**
    * 异步校验valueCode是否存在
    * 
    * @param {FormControl} control 
    * @returns {Promise<true>} 
    * 
    * @memberof DicKeyEditComponent
    */
    valueDisplayAsnyValidator(control: FormControl): any {
        return this.setofvalueService.hasValueDisplay(control.value, this.currentEntity.valueId, this.currentEntity.keyId)
            .map(res => res ? { exist: true } : null);
    }
    // rang(min: number, max: number): ValidatorFn {
    //     return (control: AbstractControl): { [key: string]: any } => {
    //         if (control.value as number) {
    //             const result = control.value as number;
    //             return !(result >= min && result <= max) ? { 'rang': { result } } : null
    //         }
    //         return null;

    //     };
    // }
    /**
     * 创建一个数据字典键
     * 
     * 
     * @memberof DicKeyEditComponent
     */
    onCreate() {
        if (!this.hasError()) {
            this.bladeData.isLoading = true;
            let formValue = this.formGroup.value;
            this.currentEntity.valueCode = formValue.valueCode;
            this.currentEntity.valueDisplay = formValue.valueDisplay;
            this.currentEntity.valueDefault = formValue.valueDefault;
            this.currentEntity.valueSeq = formValue.valueSeq;
            this.setofvalueService.create(this.currentEntity)
                .then(res => {
                    if (res) {
                        let parentContainerInstance = this.parentBlade.bladeContainerInstance;
                        parentContainerInstance.refresh(res);
                        this.bladeService.closeBlade(this.currentBlade);
                    }
                })
                .catch(error => this.bladeData.error = error)
                .then(res => this.bladeData.isLoading = false);
        }
    }
    /**
     * 
     * 
     * 
     * @memberof DicValueEditComponent
     */
    saveChange(): any | Promise<any> | Observable<any> {
        if (this.canSaveChange(this.currentBlade)) {
            this.bladeData.isLoading = true;
            let formValue = this.formGroup.value;
            this.currentEntity.valueCode = formValue.valueCode;
            this.currentEntity.valueDisplay = formValue.valueDisplay;
            this.currentEntity.valueDefault = formValue.valueDefault;
            this.currentEntity.valueSeq = formValue.valueSeq;
            return this.setofvalueService.update(this.currentEntity)
                .then(res => {
                    if (res) {
                        (this.parentBlade.bladeContainerInstance).refresh(res);
                        this.bladeService.closeBlade(this.currentBlade);
                        return true;
                    }
                })
                .catch(error => this.bladeData.error = error)
                .then(res => this.bladeData.isLoading = false);
        }
    }
}



// WEBPACK FOOTER //
// ./src/app/module/basic/dic/dic-value-edit/dic-value-edit.component.ts